package com.yq.testmodule.emoji

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.yq.testmodule.R

class CommentEmojiWidget @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    init {
        val mRv = RecyclerView(context)
        addView(
            mRv,
            LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )

        mRv.layoutManager = GridLayoutManager(context, 8)
        val adapter = EmojiAdapter(R.layout.item_emoji)
        mRv.adapter = adapter
        //构造表情数据
        val datas = arrayListOf<Pair<String, Int>>()
        for (item in EmojiDataManager.loadEmojiData()) {
            datas.add(Pair(item.key, item.value))
        }
        adapter.setNewData(datas)
        adapter.setOnItemClickListener { adapter, view, position ->
            mClickListener?.invoke(datas[position], false)
        }
    }

    private var mClickListener: ((iconData: Pair<String, Int>, isDelIcon: Boolean) -> Unit)? = null
    fun setOnEmojiIconClick(clickListener: (iconData: Pair<String, Int>, isDelIcon: Boolean) -> Unit) {
        mClickListener = clickListener
    }


    inner class EmojiAdapter(layoutResId: Int) :
        BaseQuickAdapter<Pair<String, Int>, BaseViewHolder>(
            layoutResId
        ) {
        override fun convert(holder: BaseViewHolder, item: Pair<String, Int>) {
            holder.setBackgroundResource(R.id.ivEmoji, item.second)
        }
    }

}